package com.marui.ch2.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer> {
    private static final int threshold=2;
    private int start;
    private int end;
    public CountTask(int start,int end){
        this.start=start;
        this.end=end;
    }
    
    @Override
    protected Integer compute() {
        int sum=0;
        boolean flag=(end-start)<=threshold;
        if(!flag){
            int mid=(end+start)/2;
            CountTask left = new CountTask(start, mid);
            CountTask right = new CountTask(mid+1, end);
            left.fork();
            right.fork();
            sum=left.join()+right.join();

        }else{
            for (int i = start; i <=end ; i++) {
                sum+=i;
            }
        }
        return sum;
    }

    public static void main(String[] args)  {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask countTask = new CountTask(1,100);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(countTask);
        try {
            System.out.println(submit.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }
}
